//
//  CollectionViewCell.m
//  网易
//
//  Created by 何欣 on 15/7/1.
//  Copyright (c) 2015年 何欣. All rights reserved.
//

#import "HomeCollectionViewCell.h"

@interface HomeCollectionViewCell  ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,strong)UILabel *label;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,assign)BOOL isDuanZi;//记录当前的话题是否为段子
@property(nonatomic,retain)HomeTableViewHeader *tabelViewHeader;
@property(nonatomic,assign)NSInteger footerRefreshAddCount;//上拉加载 添加的个数

@property(nonatomic,strong)NSMutableArray *adArray;//广告数组
@property(nonatomic,assign)NSInteger adCount;//广告个数

@end

@implementation HomeCollectionViewCell


-(instancetype)initWithFrame:(CGRect)frame{

    self  = [super initWithFrame:frame];
    if (self) {

        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [self.contentView addSubview:_tableView];
        
        _tabelViewHeader = [[HomeTableViewHeader alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 200)];
        [_tableView registerClass:[HomeTableViewCell class] forCellReuseIdentifier:@"cell"];
        [_tableView registerClass:[HomeDuanZiTableViewCell class] forCellReuseIdentifier:@"HomeDuanZiTableViewCell"];
        
        //分割线顶到头
        if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
        {
            [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        }
        if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
        {
            [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        }
        _dataSource = [NSMutableArray array];
        _adArray = [NSMutableArray array];
        _footerRefreshAddCount = RefreshCount;
        [self setupRefresh];
    }
    return self;
}
#pragma mark- delegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    return _dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (!_isDuanZi) {
        HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        if (_dataSource.count != 0) {
            [cell setDataForHomeTableViewCell:_dataSource[indexPath.row]];
        }
        
        return cell;
    }
    HomeDuanZiTableViewCell *homeDuanZicell = [tableView dequeueReusableCellWithIdentifier:@"HomeDuanZiTableViewCell"];
    CGSize size = [HXGetLabelSizeFromStr labelFitHeight:[_dataSource[indexPath.row] digest] andFontSize:17.0f];
    [homeDuanZicell setCellLableHeight:size.height text:[_dataSource[indexPath.row] digest]];
    return homeDuanZicell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (!_isDuanZi) {
        return 100;
    }
     CGSize size = [HXGetLabelSizeFromStr labelFitHeight:[_dataSource[indexPath.row] digest] andFontSize:17.0f];
     return size.height + 20;
}

//分割线顶到头
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]){
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_isDuanZi) {
        return;
    }
    
    HomeTableViewModel *model = _dataSource[indexPath.row];
    
    [self.delegate homeCollectionViewCellDidSelectTableViewCell:model.url];
    
}

#pragma mark- 获取数据

/**
 *  获取CollectionViewCell的tableView数据
 */
-(void)getDataForCollectionViewCell{
    //tid为空时，不走网络请求
    if (self.tid == NULL) {
        return;
    }
    [_dataSource removeAllObjects];
    //此接口第一个数据 为轮播图数据
    NSString *requsestUrl = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/headline/%@/0-%ld.html",_tid,_footerRefreshAddCount];
    
    [QCHttpHandler get:requsestUrl body:nil HTTPHead:nil result:QCJson success:^(id result) {
        
        
        NSArray *resultArr = [result objectForKey:_tid];
        //获取广告
        NSDictionary *adDic = resultArr[0];
        HomeAdModel *adModel = [[HomeAdModel alloc]init];
        adModel.title = [adDic objectForKey:@"title"];
        adModel.descImg = [adDic objectForKey:@"imgsrc"];
        [_adArray addObject:adModel];
        
        NSString *hasAD = [NSString stringWithFormat:@"%@",[adDic objectForKey:@"hasAD"]];
        NSLog(@"hasAD ~~~~~~%@",hasAD);
        if ([hasAD integerValue] > 0) {
            _adCount = [hasAD integerValue];
            [self getAdDataForTabelViewHeader];
        }else{
            [_tabelViewHeader setHeaderData:self.adArray];
        }
        for (int i = 1; i < resultArr.count - 1; i++) {
            HomeTableViewModel *tableViewModel = [HomeTableViewModel homeTableViewModelWithDictionary:resultArr[i]];
            [self.dataSource addObject:tableViewModel];
            [self.tableView reloadData];
            //获取到数据停止刷新数据
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
        }
    } failure:^(NSError *error){
    }];
}
/**
 *  获取段子数据
 */
-(void)getDuanZiDataForCollectionViewCell{
    [_dataSource removeAllObjects];
    NSString *requestUrl = [NSString stringWithFormat:@"http://c.3g.163.com/recommend/getChanRecomNews?channel=duanzi&passport=&devId=CE80EFE4-9CE9-4E06-B117-DFA8DE7893F1&size=%ld",_footerRefreshAddCount];
    [QCHttpHandler get:requestUrl body:nil HTTPHead:nil result:QCJson success:^(id result) {
        for (NSDictionary *dic in [result objectForKey:@"段子"] ) {
            HomeDuanZiTableViewModel *model = [HomeDuanZiTableViewModel homeDuanZiTableViewModelWithDictionary:dic];
            [self.dataSource addObject:model];
            [_tableView reloadData];
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
        }
    } failure:^(NSError *error) {
        
    }];
}

/**
 *  获取广告消息
 */

-(void)getAdDataForTabelViewHeader{
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:datenow];
    NSDate *localeDate = [datenow  dateByAddingTimeInterval: interval];
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[localeDate timeIntervalSince1970]];

    NSString *requestUrl = [NSString stringWithFormat:@"http://g1.163.com/madrs?app=7A16FBB6&platform=ios&category=%@&location=10,11,20,21,22,23&timestamp=%@&uid=",_tid,timeSp];
    requestUrl = [requestUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [QCHttpHandler get:requestUrl body:nil HTTPHead:nil result:QCJson success:^(id result) {
        
        NSLog(@"%@",requestUrl);
        for (NSDictionary *dic in result) {
            for (NSDictionary *adDic in [dic objectForKey:@"ads"]) {
                HomeAdModel *adModel = [[HomeAdModel alloc]init];
                adModel.title = [adDic objectForKey:@"main_title"];
                adModel.descImg = [[adDic objectForKey:@"res_url"] objectAtIndex:0];
                [self.adArray addObject:adModel];
                NSLog(@"🍎🍎🍎🍎🍎%@ %@",adModel.title,adModel.descImg);
            }
        }
        [_tabelViewHeader setHeaderData:self.adArray];

        NSLog(@"~~~~~~~~~~~~~%ld",self.adArray.count);
    } failure:^(NSError *error) {
      
        NSLog(@" error :%@",error);
        
    }];
}

/**
 *  重写tid set方法
 *
 *  @param tid
 */
-(void)setTid:(NSString *)tid{
    //cell的重用机制，重用时不走初始化方法，
    //在collectionView切换cell时,重新设置tid,获取数据，
    //获取数据前,数组清空 并刷新tableView 防止数组中有上一个cell的数据，并且tableView显示
    [_adArray removeAllObjects];
    [_dataSource removeAllObjects];
    [_tableView reloadData];
    //如果tid 和 DuanZiTid相同，tableView 不设置header 请求段子的网络数据
    if ([tid isEqualToString:DuanZiTid]) {
        _isDuanZi = YES;
        _tableView.tableHeaderView.hidden = YES;
    }else {
        _isDuanZi = NO;
        _tid = tid;
        _tableView.tableHeaderView = _tabelViewHeader;
    }

    [_tableView.header beginRefreshing];

}

#pragma mark 刷新
- (void)setupRefresh
{
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    [self.tableView.header beginRefreshing];
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
}

-(void)headerRefresh{
  
    if (_isDuanZi) {
        [self getDuanZiDataForCollectionViewCell];
        return;
    }
    [self getDataForCollectionViewCell];
}

-(void)footerRefresh{

    _footerRefreshAddCount = RefreshCount + 20;
    [_tableView.footer beginRefreshing];
    

}

@end
